package util;

import entities.Folder;
import entities.TreeNode;
import entities.User;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class JsonHelper {
    
    public static JSONObject getFolderTree(User user) {
        return encodeFolder(user.getTreeRoot());
    }
    
    private static JSONObject encodeFolder(Folder folder) {
        
        JSONObject jsonFolder = new JSONObject();
        JSONArray childsJson = new JSONArray();
        long parentId = (folder.getParent() != null) ? folder.getParent().getId() : -1;
        
        // Add properties to JSON object
        jsonFolder.put("name",      folder.getName());
        jsonFolder.put("id",        folder.getId());
        jsonFolder.put("created",   folder.getDateCreated().getTimeInMillis());
        jsonFolder.put("modified",  folder.getDateModified().getTimeInMillis());
        jsonFolder.put("childs",    childsJson);
        jsonFolder.put("parentId",  parentId);
        
        Iterator<TreeNode> itr = folder.getChilds().iterator();
        while (itr.hasNext()) {
            TreeNode child = itr.next();
            if (child instanceof Folder) {
                childsJson.add(encodeFolder((Folder)child));
            }
        }
        
        return jsonFolder;
    }
}
